<script setup lang="ts">
import type { Props, Emits } from './utils/types'
import type { FormRules, FormInstance } from 'element-plus'
import { formatBytes } from '@/utils/index'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useAuth } from '@/stores/index'
import APIUploadMaterial from '@/api/upload-material'
import { EditPen, CloseBold } from '@element-plus/icons-vue'
import { getVideoResolution } from '@/utils/index'
import SelectMusic from '@/components/SelectMusic/index.vue'
import APICommon from '@/api/common'

const dialogVisible = shallowRef(false)
const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
watch($props, (newValue) => {
    dialogVisible.value = newValue.modelValue
}, { immediate: true })
watch(dialogVisible, (newValue) => {
    if (newValue) {
        tvideoGetEditSDetail()
    }

    $emit('update:modelValue', newValue)
})
function onBeforeClose() {
    formData.value = {}
    dialogVisible.value = false
}
const dialogInnerVisible = shallowRef<boolean>(false)
const formData = ref<any>({
    profit: 50
})
const { info } = storeToRefs(useAuth())

function handlePriceClear() {
    formData.value.authors.forEach((item: any) => {
        item.market_price = 0
        item.get_price = 0
    })
}
const editSDetail = ref<any>({})

function handlePriceAuto() {
    formData.value.authors.forEach((item: any, index: number) => {
        if (!editSDetail.value.AuthorList) return
        item.market_price = editSDetail.value?.AuthorList[index]?.market_price
        item.get_price = editSDetail.value?.AuthorList[index]?.get_price
    })
}

const rules = reactive<FormRules<any>>({
    title: [{
        required: true, message: '请输入标题', trigger: 'blur',
    }, {
        max: 40, message: '标题不可以超过40字', trigger: 'blur'
    }],
    brief: [{
        required: true, message: '请输入描述', trigger: 'blur'
    }, {
        max: 200, message: '作品介绍不可以超过40字', trigger: 'blur'
    }],
    key: [{
        required: true, message: '请输入关键字', trigger: 'blur'
    }, {
        pattern: /^([\u4e00-\u9fa5a-zA-Z0-9]+)(\/[\u4e00-\u9fa5a-zA-Z0-9]+){4,}$/,
        message: '不可少于5个关键词，并且不可有特殊符号',
        trigger: 'blur'
    }],
    template_pid: [{
        required: true, message: '请选择上级模板', trigger: 'blur'
    }],
    template_id: [{
        required: true, message: '请选择下级模板', trigger: 'blur'
    }],
    template_three_id: [{
        required: true, message: '请选择第三级模板', trigger: 'blur'
    }],
    remark: [{
        required: true, message: '请输入备注', trigger: 'blur'
    }],
    profit: [{
        required: true, message: '请选择利润', trigger: 'blur'
    }]
})


const ruleFormRef = shallowRef<FormInstance>()

function submitChange() {
    ruleFormRef.value?.validate((valid, fields) => {
        if (valid) {
            const form = { ...formData.value }
            form.authors = JSON.stringify(form.authors)
            form.shop_id = info.value.shop_id
            const loading = ElLoading.service({ lock: true })
            APIUploadMaterial.changeTemVideo(form).then(({ msg }) => {
                ElMessage.success('提交成功')
                onBeforeClose()
                $emit('get-list')
            }).finally(() => {
                loading.close()
            })
        } else {
            if (fields?.title && fields?.title?.length != 0) {
                ElMessage.error(fields?.title[0]?.message)
            } else if (fields?.brief && fields?.brief?.length != 0) {
                ElMessage.error(fields?.brief[0]?.message)
            } else if (fields?.key && fields?.key?.length != 0) {
                ElMessage.error(fields?.key[0]?.message)
            } else if (fields?.template_pid && fields?.template_pid?.length != 0) {
                ElMessage.error(fields?.template_pid[0]?.message)
            } else if (fields?.template_id && fields?.template_id?.length != 0) {
                ElMessage.error(fields?.template_id[0]?.message)
            } else if (fields?.template_three_id && fields?.template_three_id?.length != 0) {
                ElMessage.error(fields?.template_three_id[0]?.message)
            } else if (fields?.remark && fields?.remark?.length != 0) {
                ElMessage.error(fields?.remark[0]?.message)
            } else if (fields?.profit && fields?.profit?.length != 0) {
                ElMessage.error(fields?.profit[0]?.message)
            }
        }
    })
}


function tvideoGetEditSDetail() {
    const goods_id = $props.goods_id
    if (!goods_id) return
    APIUploadMaterial.tvideoGetEditSDetail(goods_id).then(({ data }) => {
        editSDetail.value = data
        formData.value.goods_id = goods_id
        formData.value.authors = JSON.parse(JSON.stringify(editSDetail.value.AuthorList))
        formData.value.format = data.file.split('.').at(-1)
        formData.value.title = editSDetail.value.title
        formData.value.brief = editSDetail.value.brief
        formData.value.key = editSDetail.value.key
        formData.value.profit = editSDetail.value.profit
        formData.value.template_pid = editSDetail.value.template_pid
        formData.value.template_id = editSDetail.value.template_id
        formData.value.template_three_id = editSDetail.value.template_three_id
        formData.value.remark = editSDetail.value.remark
        formData.value.bg_music = data.bg_music
        formData.value.sprite_list = editSDetail.value.sprite_list
        return getVideoResolution(data.file)
    }).then(({ width, height }) => {
        formData.value.width = width
        formData.value.height = height
    })
}

const templateSelectList = ref<any[]>([])

watch(() => formData.value.template_pid, (newValue) => {
    if (!newValue) return
    getTemplateSelect(newValue)
})

function getTemplateSelect(id: number) {
    APIUploadMaterial.getTemplateSelect(id).then(({ data }) => {
        templateSelectList.value = data
    })
}

const threeLevelSelectList = ref<any[]>([])

function getThreeLevel(id: number) {
    APIUploadMaterial.getTemplateSelect(id).then(({ data }) => {
        threeLevelSelectList.value = data
        if (threeLevelSelectList.value.length == 0) {
            formData.value.template_three_id = undefined
        }
    })
}

watch(() => formData.value.template_id, (newValue) => {
    if (!newValue) return
    getThreeLevel(newValue)
})


const dialogMusicVisible = shallowRef<boolean>(false)

function handleJumpView(type: string, mark: string) {
    window.open(`${import.meta.env.VITE_APP_WEB_URL}/agreement?type=${type}&mark=${mark}`)
}

const refBackground = shallowRef<HTMLInputElement>()

function handleChangeSprite() {
    ElMessageBox.confirm(
        '是否更换雪碧图？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        refBackground.value?.click()
    }).catch(() => {
        ElMessage.info('已取消')
    })
}


function onUploadBackgroundChange(e: Event) {
    const dom = (e.target as HTMLInputElement)
    if (!dom.files) return
    if (!['image/png', 'image/webp', 'image/jpeg', 'image/gif', 'image/bmp', 'image/svg+xml', 'image/x-icon'].includes(dom.files[0].type)) {
        dom.value = ''
        ElMessage.error('只能上传图片文件，请重新选择文件。')
        return
    }

    const fileSize = dom.files[0].size
    const fileSizeMB = fileSize / (1024 * 1024)
    if (fileSizeMB > 5) return ElMessage.error('上传文件大小不能超过5MB，请重新选择文件。')
    const form = new FormData()
    form.append('file', dom.files[0])

    const changeFileLoading = ElLoading.service({ lock: true })

    APICommon.uploadFile(form).then(({ data }) => {
        formData.value.sprite_list = data.file
    }).finally(() => {
        changeFileLoading.close()
    })
}
function handleFree() {
    formData.value.authors.forEach((item: any) => {
        item.get_price = 0
    })
}

</script>

<template>
    <el-dialog v-model="dialogVisible" title="视频作品编辑" width="1124" :before-close="onBeforeClose" destroy-on-close
        :show-close="false">
        <template #header>
            <DialogClose title="视频作品编辑" @close="onBeforeClose" />
        </template>
        <el-dialog class="zuoping-edit" v-model="dialogInnerVisible" width="1000" :show-close="false">
            <template #header>
                <DialogClose title="视频价格编辑" @close="dialogInnerVisible = false" />
                <EditQuestionFilled style="position: absolute; top: 11px; left: 98px;" />
            </template>
            <el-table class="price-edit" :data="formData.authors">
                <el-table-column label="板块">视频</el-table-column>
                <el-table-column prop="using_body" label="授权类型" />
                <el-table-column label="授权详情信息（授权信息可编辑）" min-width="400" v-slot="{ row }">
                    <div v-if="!row.isShowAuthDetilEdit">
                        {{ row.auth_detail }}
                        <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                            @click="row.isShowAuthDetilEdit = true">
                            <EditPen />
                        </el-icon>
                    </div>
                    <el-input v-model="row.auth_detail" v-else :ref="(el: any) => el?.focus()"
                        @blur="row.isShowAuthDetilEdit = undefined" />
                </el-table-column>
                <el-table-column label="市场价（元）" min-width="100" v-slot="{ row }">
                    <div v-if="!row.isShowMarketPriceEdit">
                        {{ row.market_price }}
                        <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                            @click="row.isShowMarketPriceEdit = true">
                            <EditPen />
                        </el-icon>
                    </div>
                    <el-input v-model="row.market_price" v-else :ref="(el: any) => el?.focus()"
                        @blur="row.isShowMarketPriceEdit = undefined" />
                </el-table-column>
                <el-table-column label="到手价（元）" min-width="100" v-slot="{ row }">
                    <div v-if="!row.isShowGetPriceEdit">
                        {{ row.get_price }}
                        <el-icon color="#0F40F5" size="20" style="cursor: pointer;position: relative;top: 4px;"
                            @click="row.isShowGetPriceEdit = true">
                            <EditPen />
                        </el-icon>
                    </div>
                    <el-input v-model="row.get_price" v-else :ref="(el: any) => el?.focus()"
                        @blur="row.isShowGetPriceEdit = undefined" />
                </el-table-column>
            </el-table>
            <div class="price-edit-btn">
                <button type="button" style="background-color: #e6a23c" @click="handleFree">免费售卖</button>
                <button type="button" @click="handlePriceClear">清除价格</button>
                <button type="button" @click="handlePriceAuto">使用模板价格</button>
            </div>
            <button class="price-edit-submit" @click="dialogInnerVisible = false">
                确认
            </button>
        </el-dialog>
        <SelectMusic v-model="dialogMusicVisible" v-model:getBgMusic="formData.bg_music" />
        <div class="no-pass" v-if="editSDetail.status == 2">
            不通过原因：{{ editSDetail.reason }}
        </div>
        <div class="template-edit">
            <div class="left">
                <video v-if="editSDetail.sample" :src="editSDetail.sample" controls></video>
                <img v-if="formData.sprite_list" :src="formData.sprite_list" alt="sprite_list"
                    @click="handleChangeSprite">
                <input ref="refBackground" type="file" @change="onUploadBackgroundChange" style="display: none;"
                    accept="image/*">
                <button class="btns-left-btn btns-left-btn-music" @click="dialogMusicVisible = true">
                    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
                        viewBox="0 0 32 32" width="20" height="20"
                        style="border-color: rgba(0,0,0,0);border-width: bpx;border-style: undefined" filter="none">
                        <g>
                            <path
                                d="M16 5.333c-5.891 0-10.667 4.776-10.667 10.667v0h4c1.473 0 2.667 1.194 2.667 2.667v0 6.667c0 1.473-1.194 2.667-2.667 2.667v0h-4c-1.473 0-2.667-1.194-2.667-2.667v0-9.333c0-7.364 5.969-13.333 13.333-13.333s13.333 5.969 13.333 13.333v9.333c0 1.473-1.194 2.667-2.667 2.667v0h-4c-1.473 0-2.667-1.194-2.667-2.667v0-6.667c0-1.473 1.194-2.667 2.667-2.667v0h4c0-5.891-4.776-10.667-10.667-10.667v0zM5.333 18.667v6.667h4v-6.667h-4zM22.667 18.667v6.667h4v-6.667h-4z"
                                fill="rgba(248.88,19.89,19.89,1)">
                            </path>
                        </g>
                    </svg>
                    选择背景音乐
                </button>
                <div class="ative" v-if="formData.bg_music">
                    已选择背景音乐
                    <div class="delete" @click="formData.bg_music = undefined">
                        <el-icon color="#ffffff" size="11px">
                            <CloseBold />
                        </el-icon>
                    </div>
                </div>
            </div>
            <el-form class="form" ref="ruleFormRef" :model="formData" :rules="rules" :show-message="false">
                <div class="middle">
                    <div class="template-info">
                        <div>编号：{{ editSDetail.code }}</div>
                        <div>日期：{{ editSDetail.create_time }}</div>
                        <div>大小：{{ formatBytes(Number(editSDetail?.file_size)) }}</div>
                    </div>
                    <div class="item-input">
                        <el-form-item prop="title" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.title" placeholder="标题：请输入不超过40字的标题"
                                style="height: 40px;" input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                        </el-form-item>
                    </div>
                    <div class="text">准确描述产品将更易被搜索出来；<span @click="handleJumpView('help', 'title')">标题填写技巧</span></div>
                    <div class="item-input">
                        <el-form-item prop="brief" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.brief" placeholder="描述：请输入不超过200字的作品介绍" type="textarea"
                                input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                        </el-form-item>
                    </div>
                    <div class="text">通过描述吸引更多感兴趣的用户；<span @click="handleJumpView('help', 'breif')">描述填写技巧</span></div>
                    <div class="item-input">
                        <el-form-item prop="key" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.key" placeholder="不少于5个关键词，关键词与关键词以《 / 》符号隔开；"
                                style="height: 40px;" input-style="font-family: 'SOURCEHANSANSCN-EXTRALIGHT'" />
                        </el-form-item>
                    </div>
                    <div class="text">可快速使用关键词查找到作品；<span @click="handleJumpView('help', 'keyword')">关键词填写技巧</span>
                    </div>
                    <div class="item-input ">
                        <div class="select-box">
                            <el-form-item prop="template_pid" style="margin: 0; width: 50%;">
                                <el-select class="select-height" v-model="formData.template_pid">
                                    <el-option v-for="item in editSDetail.template" :key="item.id" :label="item.title"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="template_id" style="margin: 0;width: 50%;">
                                <el-select class="select-height" v-model="formData.template_id">
                                    <el-option v-for="item in templateSelectList" :key="item.id" :label="item.title"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="template_three_id" style="margin: 0;width: 50%;"
                                v-if="threeLevelSelectList.length != 0">
                                <el-select class="select-height" v-model="formData.template_three_id">
                                    <el-option v-for="item in threeLevelSelectList" :key="item.id" :label="item.title"
                                        :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                    </div>
                    <div class="text">选择视频模板使用软件及软件版本</div>
                    <div class="item-input">
                        <el-form-item prop="remark" style="margin: 0;width: 100%;">
                            <el-input v-model="formData.remark" placeholder="备注：例：全部可编辑；文字以及定版画面可修改"
                                style="height: 40px;" />
                        </el-form-item>
                    </div>
                    <div class="text">填写视模板可编辑的范围</div>
                </div>
                <div class="right">
                    <div class="market-price">
                        <div class="item-input">
                            <button type="button" @click="dialogInnerVisible = true">销售价格</button>
                        </div>
                        <p>按照授权类型填写销售价格</p>
                    </div>
                    <div class="market-price">
                        <div class="item-input">
                            <el-form-item prop="profit" style="margin: 0;width: 100%;">
                                <el-select v-model="formData.profit" placeholder="利润">
                                    <el-option v-for="(item, index) in editSDetail.profit_percentage" :key="index"
                                        :label="item.type" :value="item.title">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <p>选择销售出去作品分给平台的利润</p>
                    </div>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false" style="width: 216px; height: 40px;">取消</el-button>
                <el-button color="rgb(15 64 240)" @click="submitChange" style="width: 216px; height: 40px;">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss">
.price-edit {
    .el-table__header {
        .cell {
            font-family: 'SOURCEHANSANSCN-REGULAR';
        }
    }

    .el-table__body-wrapper {
        .cell {
            font-family: 'SOURCEHANSANSCN-LIGHT';
        }
    }
}
</style>

<style lang="scss" scoped>
.template-edit {
    display: flex;
    justify-content: center;
    gap: 0 22px;
    margin-top: 30px;

    .ative {
        position: relative;
        width: 98px;
        margin-top: 20px;

        .delete {
            position: absolute;
            right: -10px;
            top: -10px;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background-color: #F91B1B;
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
        }
    }

    .btns-left-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 38px;
        border: none;
        border-radius: 5px;
        font-size: 14px;
        cursor: pointer;
        background-color: rgba(55, 133, 242, 1);
        color: rgba(255, 255, 255, 1);
        gap: 0 10px;
    }

    .btns-left-btn-music {
        background-color: #ffffff;
        color: #ff0000;
        border: 1px dashed rgba(206, 206, 206, 1);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0 10px;
        margin: 0 auto;
        margin-top: 20px;
    }

    .right {
        width: 232px;

        .item-input {
            display: flex;

            &::before {
                content: '*';
                margin-right: 5px;
                font-size: 20px;
                font-weight: 700;
                color: #F91B1B;
            }
        }

        .market-price {
            button {
                width: 231px;
                height: 40px;
                border-radius: 5px;
                background-color: rgba(15, 64, 245, 1);
                color: rgba(255, 255, 255, 1);
                font-size: 14px;
                border: none;
                cursor: pointer;
            }

            p {
                color: rgba(154, 154, 154, 1);
                font-size: 14px;
                margin-bottom: 20px;
                margin-left: 15px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }
    }

    .middle {
        width: 500px;

        .select-box {
            display: flex;
            gap: 0 32px;
            width: 100%;
        }

        .item-input {
            display: flex;

            &::before {
                content: '*';
                margin-right: 5px;
                font-size: 20px;
                font-weight: 700;
                color: #F91B1B;
            }
        }

        .text {
            margin-left: 20px;
            color: rgba(154, 154, 154, 1);
            font-size: 14px;
            line-height: 1.6em;
            margin-bottom: 20px;
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';

            span {
                color: #3F90F7;
                cursor: pointer;
            }
        }

        .template-info {
            display: flex;
            gap: 0 10px;
            margin-bottom: 20px;
        }
    }

    .form {
        display: flex;
        gap: 0 22px;
    }

    .left {
        width: 256px;

        video {
            display: block;
            width: 100%;
            height: 143px;
            object-fit: cover;
        }

        img {
            display: block;
            width: 100%;
            height: 143px;
            object-fit: cover;
            cursor: pointer;
        }
    }
}

.price-edit-submit {
    width: 230px;
    height: 40px;
    border-radius: 5px;
    background-color: rgba(249, 20, 20, 1);
    color: rgba(255, 255, 255, 1);
    font-size: 14px;
    border: none;
    display: block;
    margin: 0 auto;
    cursor: pointer;
    margin-bottom: 40px;
    margin-top: 20px;
}

.price-edit-btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 17px;
    gap: 0 26px;

    button {
        display: block;
        width: 120px;
        height: 40px;
        color: #ffffff;
        background-color: #3F90F7;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 14px;
    }
}

.price-edit {
    width: 100%;
    margin-top: 20px;
}

.no-pass {
    position: absolute;
    top: 11px;
    left: 135px;
    color: red;
    font-weight: 700;
}

.push-item {
    position: relative;
    border-radius: 5px;
    overflow: hidden;



    .push-video-item-btns {
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        height: 30px;
        background-color: rgba(0, 0, 0, 0.292);
        z-index: 999;
        bottom: 0;
        color: #ffffff;
        font-size: 13px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 40px;

        span {
            cursor: pointer;
        }
    }

    &:hover .push-item-mask {
        opacity: 1;
    }

    .push-item-mask {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.292);
        opacity: 0;
        transition: all .2s;

        .push-item-play {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 135px;
        }

        .push-item-btns {
            box-sizing: border-box;
            width: 100%;
            height: 30px;
            color: #ffffff;
            font-size: 13px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 40px;

            span {
                cursor: pointer;
            }
        }
    }

    img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

}
</style>